const { defineConfig } = require('@vue/cli-service')
const bodyParser = require('body-parser')
const Mock = require('mockjs')

// 模拟书城书架

const data = Mock.mock({
  'book|50': [
    {
      'id|+1': 1,
      'bookName|+1': [
        '重生之门',
        '请叫我总监',
        '曾焕转',
        '法医秦明',
        'vue开发大全',
        'react渐进式开发',
        '高级全栈工程师',
        '高级程序设计',
        'javascript数据结构和算法',
        'js从入门到放弃',
        '微信小程序实战讲解',
      ],
      bookPrice: '@integer(1,100)',
      img: '@image(200x200,@color)',
      content: `<h1>@cparagraph(500)</h1>`,
      createTime: '@date(yyyy-MM-dd hh:mm:ss)',
    },
  ],
})

const userInfo = {
  admin: {
    avatar: 'https://www.robohash.org/2',
    nickname: 'wyp0712',
  },
  devin: {
    avatar: 'https://www.robohash.org/3',
    nickname: 'devin',
  },
  zhangsan: {
    avatar: 'https://www.robohash.org/8',
    nickname: 'zhangsan',
  },
}

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined')
      }

      const { app } = devServer

      app.use(bodyParser.json())

      // 登陆接口
      app.post('/api/login', (req, res) => {
        const { username, password } = req.body
        if (userInfo[username]) {
          res.send({
            code: 0,
            msg: 'sucess',
            data: {
              token: `${username}_${Date.now()}`,
              userInfo: userInfo[username],
            },
          })
        } else {
          res.send({
            code: -1,
            msg: 'fail',
          })
        }
      })

      // 2. 列表接口
      app.get('/api/bookList', (req, res) => {
        const { page = 1, size = 10 } = req.query
        res.send({
          code: 0,
          msg: 'success',
          data: data.book.slice((page - 1) * size, page * size),
        })
      })

      // 3. 详情接口
      app.get('/api/detail', (req, res) => {
        const { id } = req.query
        res.send({
          code: 0,
          msg: 'success',
          data: data.book.filter((v) => v.id == id),
        })
      })

      return middlewares
    },
  },
})
